﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace M3U8下载神器
{
    public partial class PipeForm : Form
    {
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 7473);//定义一网络端点
                                                              // Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
        HttpListener httpListener;

        bool run = false;
        public PipeForm()
        {
            InitializeComponent();
            FormClosing += (o, e) =>
            {
                run = false;
                httpListener?.Close();
            };
        }

        private void PipeForm_Load(object sender, EventArgs e)
        {
            try
            {
                Debug.WriteLine("zheng zai qi dong");
                httpListener = new HttpListener();
                httpListener.Prefixes.Add("http://127.0.0.1:63883/");
                httpListener.Start();
                run = true;
                Debug.WriteLine(httpListener.IsListening?"启动成功":"启动失败!");
            }
            catch (Exception)
            {
                MessageBox.Show("启动失败!");
                return;
            }

            ThreadPool.QueueUserWorkItem(delegate
            {
                
                while (run)
                {
                    try
                    {
                       Read(httpListener.GetContext());
                    }
                    catch (Exception)
                    {            
                    }
                }
            });
        }
        public void Read(HttpListenerContext context)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    var reader = new StreamReader(context.Request.InputStream);
                    var msg = reader.ReadToEnd();//读取传过来的信息
                    int index = msg.IndexOf("data=");
                    if (index != 0) return;

                    var data = msg.Substring(5);
                    Debug.WriteLine(context.Request.HttpMethod + "data:" + data);
                    context.Response.StatusCode = 200;
                    byte[] send = Encoding.UTF8.GetBytes("OK");
                    context.Response.Close(send, false);
                    var line = System.Web.HttpUtility.UrlDecode(data, Encoding.Unicode); ;
                    if (line != null)
                        OpenTask(line);
                }
                catch (Exception)
                {

                    throw;
                }
            });
        }
        private void OpenTask(string line)
        {
            var ss = line.Split('\t');
            this.Invoke(new Action(() =>
            {
                try
                {
                    NewTaskDialog newTaskDialog = new NewTaskDialog();
                    newTaskDialog.SetFileNameToSavePath(ss[0]);
                    newTaskDialog.Url = ss[1];
                    if (newTaskDialog.ShowDialog() == DialogResult.OK && newTaskDialog.Package.Begin())
                    {
                        var form = new DownloadForm();
                        form.Build(newTaskDialog.Package);
                        form.Show();
                        form.Start();
                    }
                }
                catch (Exception)
                {

                    throw;
                }
            }));
        }

    }
}
